import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:yyshort/common/apis/video_api.dart';
import 'package:yyshort/common/model/banner_model.dart';
import 'package:yyshort/common/model/video_model.dart';
import 'package:yyshort/pages/ali_player/preload/ali_player_preload.dart';
import 'package:yyshort/pages/ali_player/short_video/short_video/short_video_item.dart';
import 'state.dart';

/// 短视频页面的控制器
class ShortVideoController extends GetxController {
  /// 状态实例
  final ShortVideoState state;

  late dynamic superPageModel;

  late BannerModel bannerModel;

  final bool isforyouPage;

  /// 构造函数，接收预加载参数
  ShortVideoController({
    this.isforyouPage = false, // 默认值设为false
    bool preload = true,
  }) : state = ShortVideoState(preload: preload);

  //

  @override
  void onInit() {
    super.onInit();
    _initPreloader();
    state.isforyouPage.value = isforyouPage;
    //获取arguments参数（复杂对象）
    if (Get.arguments != null) {
      Map dic = Get.arguments as Map;
      state.isforyouPage.value = dic['isforyouPage']; // 强转为自定义对象
      superPageModel = dic['model'];
    }

    if (state.videoInfoList.isEmpty) {
      _loadData();
    }

    _setupPageListener();
  }

  @override
  void onClose() {
    // 释放资源
    state.aliPlayerPreload.destroy();
    if (state.preload) {
      state.preloadPageController.dispose();
    } else {
      state.pageController.dispose();
    }
    super.onClose();
  }

  /// 初始化预加载器
  void _initPreloader() {
    state.aliPlayerPreload = AliPlayerPreload(
      context: Get.context!,
      enableCoverUrlStrategy: true,
    );
  }

  /// 设置页面监听
  void _setupPageListener() {
    if (state.preload) {
      state.preloadPageController.addListener(_onPageChanged);
    } else {
      state.pageController.addListener(_onPageChanged);
    }
  }

  /// 加载视频数据
  Future _loadData() async {
    try {
      // ignore: prefer_typing_uninitialized_variables
      final videoList;
      if (state.isforyouPage.value) {
        videoList = await VideoAPI.for_you_videos();
      } else {
        BannerModel model = superPageModel as BannerModel;
        VideoModel videoModel = await VideoAPI.video_info(
          int.parse(model.content!),
        );
        videoList = videoModel.episodeList;
      }
      state.videoInfoList.assignAll(videoList);
      _completeLoading();
    } catch (e) {
      _handleLoadingError("Exception: $e");
    }
  }

  /// 完成加载后的公共操作
  void _completeLoading() {
    // 设置预加载器数据
    state.aliPlayerPreload.setItems(state.videoInfoList);
    state.aliPlayerPreload.moveTo(state.currentIndex.value);

    // 动态初始化 GlobalKey
    state.itemKeys.clear();
    state.itemKeys.addAll(
      List.generate(
        state.videoInfoList.length,
        (_) => GlobalKey<ShortVideoItemState>(),
      ),
    );

    state.isLoading.value = false;
  }

  /// 处理加载错误
  void _handleLoadingError(String errorMessage) {
    print("[ShortVideoPage][error]: $errorMessage");
    state.isLoading.value = false;
  }

  /// 页面变化监听器
  void _onPageChanged() {
    // 获取当前页面索引
    final newPageIndex = state.preload
        ? state.preloadPageController.page?.round() ?? 0
        : state.pageController.page?.round() ?? 0;

    // 如果当前页面索引和新页面索引相同，则不执行任何操作
    if (state.currentIndex.value == newPageIndex) {
      return;
    }

    print(
      "[ShortVideoPage]${'-' * 30}[index][${state.currentIndex.value}->$newPageIndex]",
    );

    // 更新当前页面索引
    state.currentIndex.value = newPageIndex;

    // 更新预加载器浮标
    state.aliPlayerPreload.moveTo(newPageIndex);

    // 暂停所有后台 item
    pauseAllExceptCurrent(newPageIndex);
  }

  /// 暂停所有后台 item
  void pauseAllExceptCurrent(int currentIndex) {
    for (int i = 0; i < state.itemKeys.length; i++) {
      if (i != currentIndex) {
        // 暂停非当前 item
        state.itemKeys[i].currentState?.pause();
      } else if (i == currentIndex) {
        // 恢复当前 item
        state.itemKeys[i].currentState?.resume();
      }
    }
  }

  /// 暂停所有视频（无需参数，暂停全部视频）
  void pauseAllVideos() {
    // 遍历所有视频项，暂停所有播放中的视频
    for (int i = 0; i < state.itemKeys.length; i++) {
      // 无论是否是当前视频，全部暂停
      state.itemKeys[i].currentState?.pause();
    }
  }
}
